package com.surfmanager.dao;

import com.surfmanager.model.Profile;
import com.surfmanager.model.SurfSession;
import com.surfmanager.model.SurfSessionFilter;
import com.surfmanager.model.result.CodeType;
import com.surfmanager.util.Utilities;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;



import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class SurfSessionDAO {
	
	@Autowired
	private SessionFactory sessionFactory;
	
	
      public CodeType checkProfile(String userName, SessionFactory  sf , Session sesion){
       
        Query query = sesion.createQuery("from Profile P where P.userName = :username");
            query.setParameter("username",userName);
           List<Profile> profiles = query.list();
           if((profiles!=null) && (profiles.size()!=0)){
                return CodeType.KO_DUPLICATED_PROFILE;
            }else{
                return CodeType.OK;
            }
        }
         
        
        
        public CodeType createSurfSession(String userName,SurfSession surfSession){
            
        SessionFactory sf;
        Session sesion;
        Transaction tx=null;
        try{
            sf = HibernateUtil.getSessionFactory();
            sesion = sf.openSession();
            tx=sesion.beginTransaction();
            CodeType code = checkProfile(userName, sf, sesion);
            if(code.equals(CodeType.KO_DUPLICATED_PROFILE)){
                 Profile profile = getProfile(userName);
                surfSession.setProfile(profile);
                sesion.save(surfSession);
                code= CodeType.OK;
            } else{
                code= CodeType.KO_INEXISTING_PROFILE;   
            }
            tx.commit();
            sesion.close();
            return code;
            
        }catch(Exception ex){
            System.err.println("error:"+ex.getStackTrace()+"\n"+ex.getMessage()+"\n"+ex.getCause());
            tx.rollback();
        }
            
        return null;    
       }

    public Set<SurfSession> getSurfSessionBy(String searchParameter, String value, int parameterType) {
         try{
             System.out.println("paramteros:"+searchParameter+":"+value);
          SessionFactory  sf = HibernateUtil.getSessionFactory();
           Session sesion = sf.openSession();
           //Transaction tx=sesion.beginTransaction();
          Query query=null;
             if(parameterType==0){ //String
                String queryPattern = "from SurfSession S where S."+searchParameter+" = :parametervalue";
                query = sesion.createQuery(queryPattern);
                query.setParameter("parametervalue",value);

             }else if(parameterType==1){//int
                  
                 String queryPattern = "from SurfSession S where S."+searchParameter+" = :parametervalue";
                  query = sesion.createQuery(queryPattern);
                  query.setParameter("parametervalue",Integer.parseInt(value));
           
             }else if(parameterType==2){//double
                String queryPattern = "from SurfSession S where S."+searchParameter+" = :parametervalue";
                  query = sesion.createQuery(queryPattern);
                  query.setParameter("parametervalue",Double.parseDouble(value));
           
             }else if(parameterType==3){//date
                String queryPattern = "from SurfSession S where S."+searchParameter+" = :parametervalue";
                  query = sesion.createQuery(queryPattern);
                  query.setParameter("parametervalue",Utilities.getDateFromString(value));
           
             }else if(parameterType==4){ //username
                String queryPattern = "from SurfSession S where S.profile.userName = :parametervalue";
                query = sesion.createQuery(queryPattern);
                query.setParameter("parametervalue",value);

             }
           List<SurfSession> surfSessions = query.list();
            sesion.close();
            if(surfSessions!=null){
                return (new TreeSet<SurfSession>(surfSessions));
            }else{
                return null;
            }
             }catch(Exception ex){
                   System.err.println("error Amine:"+ex.getStackTrace()+"\n"+ex.getMessage()+"\n"+ex.getCause());
             }
             return null;
    }
        
        
          public Profile getProfile(String userName){
       
             try{
          SessionFactory  sf = HibernateUtil.getSessionFactory();
           Session sesion = sf.openSession();
           //Transaction tx=sesion.beginTransaction();
            Query query = sesion.createQuery("from Profile P where P.userName = :username");
            query.setParameter("username",userName);
           List<Profile> profiles = query.list();
            sesion.close();
            if((profiles!=null) &&(!profiles.isEmpty())){
                System.out.println("Amine: devuelto profile");
                return profiles.get(0);
            }else{
                return null;
            }
             }catch(Exception ex){
                   System.err.println("error Amine:"+ex.getStackTrace()+"\n"+ex.getMessage()+"\n"+ex.getCause());
             }
             return null;
        }

    public Set<SurfSession> getSurfSessionByFilter(SurfSessionFilter filter) {
    
    
     try{
           SessionFactory  sf = HibernateUtil.getSessionFactory();
           Session sesion = sf.openSession();
           //Transaction tx=sesion.beginTransaction();
          Query query=null;
          String queryPattern = "from SurfSession S where";
             if(filter.getUserName()!=null){ //String
                 queryPattern = queryPattern + " S.profile.userName = :userName AND";
             }
             if(filter.getDepartDate()!=null){
                  
                  queryPattern = queryPattern + " S.departDate = :departDate AND";
             }
             if(filter.getRetourDate()!=null){
                  
                  queryPattern = queryPattern + " S.retourDate = :retourDate AND";
             }
             if(filter.getMaxParticipants() !=null){
                  
                  queryPattern = queryPattern + " S.maxParticipants = :maxParticipants AND";
             }
              if(filter.getPricePerParticipant() !=null){
                  
                  queryPattern = queryPattern + " S.pricePerParticipant = :pricePerParticipant AND";
             }
               if(filter.getDepartPlace() !=null){
                  
                  queryPattern = queryPattern + " S.departPlace = :departPlace AND";
             }
               if(filter.getSessionDuration() !=null){
                  
                  queryPattern = queryPattern + " S.sessionDuration = :sessionDuration AND";
             }
              if(filter.getSessionPlace()!=null){
                  
                  queryPattern = queryPattern + " S.sessionPlace = :sessionPlace AND";
             }
               if(filter.getSessionProbability()!=null){
                  
                  queryPattern = queryPattern + " S.sessionProbability = :sessionProbability AND";
             }
               if(filter.getTransport()!=null){
                  
                  queryPattern = queryPattern + " S.transport = :transport AND";
             } 
               
                queryPattern = Utilities.getQueryWithoutSuffix(queryPattern);
                query = sesion.createQuery(queryPattern);
                query = Utilities.populateParameters(query,filter);
                
           List<SurfSession> surfSessions = query.list();
            sesion.close();
            if(surfSessions!=null){
                return (new TreeSet<SurfSession>(surfSessions));
            }else{
                return null;
            }
             }catch(Exception ex){
                   System.err.println("error Amine:"+ex.getStackTrace()+"\n"+ex.getMessage()+"\n"+ex.getCause());
             }
             return null;
    
    
    }
         
        
        
        
}
